package com.framework.boc.admin.security.sms.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.boc.admin.security.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SmsCodeAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        String subject = (String) authentication.getPrincipal();


        List<String> authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        String authoritiesStr = StringUtils.join(authorities, ",");
        Map<String, Object> claims = new HashMap<>();
        claims.put("authorities", authoritiesStr);
        final String jwt = jwtUtil.generateToken(subject, claims);

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("token", jwt);

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        out.write(mapper.writeValueAsString(res));
        out.flush();
        out.close();
    }
}
